package servlet.dept;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;
import dao.DepartmentDao;
import dbutil.DBHelper;
import entity.Admin;

public class EditDeptServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public EditDeptServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		JSONObject jsonObject = new JSONObject();
		HttpSession session = request.getSession();
		String oldName = request.getParameter("oldName");
		String newName = request.getParameter("newName");
		
		Admin admin = (Admin) session.getAttribute("admin");
		
		Connection conn = null;
		DepartmentDao departmentDao = null;
		
		try {
			conn = DBHelper.getConnection();
			conn.setAutoCommit(false);
			departmentDao = new DepartmentDao();
			if(departmentDao.updateDepartment(oldName, newName)) {// 修改成功
				jsonObject.put("retCode", "1");
				jsonObject.put("change", "");
				if(admin.getDeptName().equals(oldName)) {// 如果修改的部门是当前登录管理员的部门
					admin.setDeptName(newName);
					jsonObject.put("change", admin.getDeptName());
				}
				conn.commit();
			} else {//修改失败
				jsonObject.put("retCode", "0");
				jsonObject.put("desc", "修改失败");
				conn.rollback();
			}
			
			conn.setAutoCommit(true);
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put("retCode", "0");
			jsonObject.put("desc", "EditDeptServlet Exception");
		} finally {
			out.print(jsonObject.toString());
			out.close();
		}
	}

	public void init() throws ServletException {
	}

}
